<template>
  <view class="container">
    <view class="form-container">
      <!-- 转盘标题 -->
      <view class="form-item">
        <text class="label">转盘标题</text>
        <uni-easyinput
          v-model="editingWheel.title"
          placeholder="请输入转盘标题"
          class="input"
        ></uni-easyinput>
      </view>

      <!-- 选项列表 -->
      <view class="form-item">
        <view class="label-row">
          <text class="label">转盘选项</text>
          <text class="sub-label">(最多20个选项)</text>
        </view>

        <view
          v-for="(option, index) in editingWheel.options"
          :key="index"
          class="option-item"
        >
          <view class="option-input-group">
            <uni-easyinput
              v-model="option.text"
              placeholder="选项内容"
              class="option-input"
            ></uni-easyinput>
            <view class="option-actions">
              <uni-icons
                type="top"
                size="16"
                color="#999"
                @click="moveOptionUp(index)"
                :disabled="index === 0"
                :class="{ disabled: index === 0 }"
              ></uni-icons>
              <uni-icons
                type="bottom"
                size="16"
                color="#999"
                @click="moveOptionDown(index)"
                :disabled="index === editingWheel.options.length - 1"
                :class="{ disabled: index === editingWheel.options.length - 1 }"
              ></uni-icons>
              <uni-icons
                type="trash"
                size="16"
                color="#FF4757"
                @click="deleteOption(index)"
                :disabled="editingWheel.options.length <= 2"
                :class="{ disabled: editingWheel.options.length <= 2 }"
              ></uni-icons>
            </view>
            <view class="color-picker" @click="showColorPicker(index)">
              <view
                class="color-preview"
                :style="{ backgroundColor: option.color }"
              ></view>
            </view>
          </view>
        </view>

        <!-- 添加选项按钮 -->
        <view
          class="add-option-btn"
          @click="addOption"
          :class="{ disabled: editingWheel.options.length >= 20 }"
        >
          <uni-icons type="plus" size="24" color="#11AAAA"></uni-icons>
          <text class="add-text">添加选项</text>
        </view>
      </view>

    </view>

    <!-- 底部固定的保存按钮 -->
    <view class="bottom-fixed">
      <view class="save-btn" @click="saveWheel">保存</view>
    </view>

    <!-- 颜色选择器弹窗 -->
    <uni-popup ref="colorPickerPopup" type="bottom">
      <view class="popup-content">
        <view class="popup-header">
          <text class="popup-title">选择颜色</text>
          <uni-icons
            type="close"
            size="24"
            color="#666"
            @click="instance.refs.colorPickerPopup.close()"
          ></uni-icons>
        </view>
        <view class="color-grid">
          <view
            v-for="color in presetColors"
            :key="color"
            class="color-item"
            :style="{ backgroundColor: color }"
            @click="selectColor(color)"
          ></view>
        </view>
      </view>
    </uni-popup>
  </view>
</template>

<script>
import { ref, reactive, onMounted, getCurrentInstance } from "vue";
import hotWheelsData from "./hot-wheels.json";

export default {
  name: "EditWheel",
  setup() {
    // 编辑中的转盘数据
    const editingWheel = reactive({
      id: "",
      title: "",
      options: [
        { text: "选项一", color: "#FF6B6B" },
        { text: "选项二", color: "#4ECDC4" },
        { text: "选项三", color: "#FFD166" },
        { text: "选项四", color: "#6A0572" },
        { text: "选项五", color: "#1A535C" },
      ],
    });

    // 颜色选择器状态
    const colorPickerPopup = ref(null);
    const currentOptionIndex = ref(0);

    // 获取组件实例
    const instance = getCurrentInstance();

    // 预设颜色列表
    const presetColors = [
      "#FF6B6B",
      "#4ECDC4",
      "#FFD166",
      "#6A0572",
      "#1A535C",
      "#FF8C42",
      "#A8E6CF",
      "#DCEDC2",
      "#FFAAA6",
      "#FFD3B6",
      "#845EC2",
      "#D65DB1",
      "#FF6F91",
      "#FF9671",
      "#FFC75F",
      "#F9F871",
      "#00B894",
      "#00CEC9",
      "#0984E3",
      "#6C5CE7",
      "#FD79A8",
      "#E17055",
      "#FDCB6E",
      "#6C5CE7",
    ];

    // 获取默认颜色
    const getDefaultColor = (index) => {
      return presetColors[index % presetColors.length];
    };

    // 显示颜色选择器
    const showColorPicker = (index) => {
      currentOptionIndex.value = index;
      instance.refs.colorPickerPopup.open();
    };

    // 选择颜色
    const selectColor = (color) => {
      editingWheel.options[currentOptionIndex.value].color = color;
      instance.refs.colorPickerPopup.close();
    };

    // 添加选项
    const addOption = () => {
      if (editingWheel.options.length >= 20) {
        uni.showToast({
          title: "最多只能添20个选项",
          icon: "none",
        });
        return;
      }

      editingWheel.options.push({
        text: `选项${editingWheel.options.length + 1}`,
        color: getDefaultColor(editingWheel.options.length),
      });
    };

    // 删除选项
    const deleteOption = (index) => {
      if (editingWheel.options.length <= 2) {
        uni.showToast({
          title: "至少需要2个选项",
          icon: "none",
        });
        return;
      }

      editingWheel.options.splice(index, 1);

      // 更新选项文本
      editingWheel.options.forEach((option, i) => {
        if (!option.text || option.text.startsWith("选项")) {
          option.text = `选项${i + 1}`;
        }
      });
    };

    // 上移选项
    const moveOptionUp = (index) => {
      if (index > 0) {
        const temp = editingWheel.options[index];
        editingWheel.options[index] = editingWheel.options[index - 1];
        editingWheel.options[index - 1] = temp;
      }
    };

    // 下移选项
    const moveOptionDown = (index) => {
      if (index < editingWheel.options.length - 1) {
        const temp = editingWheel.options[index];
        editingWheel.options[index] = editingWheel.options[index + 1];
        editingWheel.options[index + 1] = temp;
      }
    };

    // 保存转盘
    const saveWheel = () => {
      // 获取页面参数，特别是isHot标记
      const pages = getCurrentPages();
      const currentPage = pages[pages.length - 1];
      const { isHot } = currentPage.options || {};
      
      // 验证标题
      if (!editingWheel.title.trim()) {
        uni.showToast({
          title: "请输入转盘标题",
          icon: "none",
        });
        return;
      }

      // 验证选项
      const emptyOptions = editingWheel.options.filter(
        (option) => !option.text.trim()
      );
      if (emptyOptions.length > 0) {
        uni.showToast({
          title: "选项内容不能为空",
          icon: "none",
        });
        return;
      }

      // 关键逻辑：
      // 如果是编辑热门转盘(isHot=true)，强制生成新ID（确保添加到我的转盘而不是更新）
      // 如果是编辑我的转盘，保留原ID（用于更新）
      let wheelToSave = { ...editingWheel };
      
      if (isHot === 'true' || isHot === true) {
        // 编辑热门转盘，生成新ID以创建新的我的转盘
        wheelToSave.id = `custom_${Date.now()}_${Math.random()
          .toString(36)
          .substr(2, 9)}`;
        console.log("保存热门转盘为新的我的转盘，新ID:", wheelToSave.id);
      } else {
        // 编辑我的转盘，确保有ID（如果没有则生成）
        if (!wheelToSave.id) {
          wheelToSave.id = `custom_${Date.now()}_${Math.random()
            .toString(36)
            .substr(2, 9)}`;
        }
        console.log("保存/更新我的转盘，ID:", wheelToSave.id);
      }

      // 保存到本地存储
      const myWheels = uni.getStorageSync("myWheels") || [];
      const existingIndex = myWheels.findIndex((w) => w.id === wheelToSave.id);

      // 检查是否是新增操作（不是编辑现有转盘）
      const isNewWheel = existingIndex === -1;

      // 限制最多保存50条记录
      const MAX_WHEELS = 50;
      if (isNewWheel && myWheels.length >= MAX_WHEELS) {
        uni.showModal({
          title: "提示",
          content: `最多只能保存${MAX_WHEELS}个转盘，新增后将删除最旧的记录，是否继续？`,
          success: (res) => {
            if (res.confirm) {
              performSaveWithLimit(wheelToSave, myWheels, existingIndex);
            }
          },
        });
      } else {
        // 直接保存
        performSaveWithLimit(wheelToSave, myWheels, existingIndex);
      }
    };

    // 执行保存逻辑（带数量限制）
    const performSaveWithLimit = (wheelToSave, myWheels, existingIndex) => {
      const MAX_WHEELS = 50;

      if (existingIndex > -1) {
        // 更新现有转盘
        myWheels[existingIndex] = wheelToSave;
        // 如果更新的不是第一个元素，则将其移到数组首项
        if (existingIndex !== 0) {
          myWheels.splice(existingIndex, 1);
          myWheels.unshift(wheelToSave);
        }
      } else {
        // 新转盘添加到数组首项
        myWheels.unshift(wheelToSave);

        // 如果超过限制，删除最旧的记录（数组末尾的元素）
        if (myWheels.length > MAX_WHEELS) {
          myWheels.splice(MAX_WHEELS);
        }
      }

      uni.setStorageSync("myWheels", myWheels);

      // 显示保存成功
      uni.showToast({
        title: "保存成功",
        icon: "success",
      });

      // 返回上一页并通知前一个页面刷新数据
      setTimeout(() => {
        // 获取上一个页面
        const pages = getCurrentPages();
        if (pages.length > 1) {
          const prevPage = pages[pages.length - 2];
          try {
            // 尝试触发上一页的数据刷新，并传递新保存的转盘id
            // 兼容Vue 3的组合式API调用方式
            if (prevPage && prevPage.$vm && typeof prevPage.$vm.refreshData === 'function') {
              prevPage.$vm.refreshData(wheelToSave.id);
              console.log('成功调用上一页的refreshData方法，传递的转盘ID:', wheelToSave.id);
            } else {
              console.warn('上一页没有refreshData方法或调用失败');
            }
          } catch (error) {
            console.error('调用上一页refreshData方法时出错:', error);
          }
        }
        uni.navigateBack();
      }, 1500);
    };

    // 返回上一页
    const goBack = () => {
      uni.navigateBack();
    };

    // 初始化
    onMounted(() => {
      // 获取页面参数
      const pages = getCurrentPages();
      const currentPage = pages[pages.length - 1];
      const { id, isHot } = currentPage.options || {};

      if (id) {
        // 先尝试从我的转盘查找
        let wheel = null;
        const myWheels = uni.getStorageSync("myWheels") || [];
        wheel = myWheels.find((w) => w.id === id);

        // 如果不是我的转盘，尝试从本地热门转盘JSON文件中查找
        if (!wheel) {
          try {
            // 直接从本地JSON文件获取热门转盘数据
            wheel = hotWheelsData.find((w) => w.id === id);
            console.log("从本地热门转盘JSON加载数据:", wheel ? "成功" : "未找到");
          } catch (e) {
            console.error("加载热门转盘数据失败:", e);
          }
        }

        if (wheel) {
          // 关键逻辑：保留原始ID用于回显，但在保存时根据isHot决定是新增还是更新
          // 如果是热门转盘(isHot=true)，编辑时保留原始ID用于数据加载，但保存时会生成新ID
          // 如果是我的转盘，保留原始ID用于更新
          editingWheel.id = wheel.id;
          editingWheel.title = wheel.title;
          editingWheel.options = JSON.parse(JSON.stringify(wheel.options));
          console.log(`加载转盘数据: ID=${id}, 标题=${wheel.title}, 是热门转盘=${isHot}`);
        }
      } else {
        // 创建全新转盘，生成默认标题
        editingWheel.id = "";
        editingWheel.title = `我的转盘${Date.now().toString().slice(-4)}`;
      }
    });

    return {
      editingWheel,
      instance,
      presetColors,
      showColorPicker,
      selectColor,
      addOption,
      deleteOption,
      moveOptionUp,
      moveOptionDown,
      saveWheel,
      performSaveWithLimit,
      goBack,
    };
  },
};
</script>

<style scoped>
.container {
  min-height: 100vh;
  background: #f5f5f5;
}

.header {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 30rpx 0;
  background: #fff;
  position: relative;
  border-bottom: 1rpx solid #eee;
}

.title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.close-icon {
  position: absolute;
  right: 30rpx;
  top: 50%;
  transform: translateY(-50%);
}

.form-container {
  padding: 30rpx;
  padding-bottom: 150rpx; /* 为底部固定按钮留出空间 */
}

.form-item {
  background: #fff;
  border-radius: 10rpx;
  padding: 30rpx;
  margin-bottom: 30rpx;
}

.label {
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 20rpx;
  display: block;
}

.label-row {
  display: flex;
  align-items: center;
  margin-bottom: 20rpx;
}

.sub-label {
  font-size: 24rpx;
  color: #999;
  margin-left: 10rpx;
}

.input {
  font-size: 28rpx;
}

.option-item {
  margin-bottom: 20rpx;
  padding: 20rpx 0;
  border-bottom: 1rpx solid #f0f0f0;
}

.option-item:last-child {
  border-bottom: none;
  margin-bottom: 0;
}

.option-input-group {
  display: flex;
  align-items: center;
  gap: 16rpx;
  margin-bottom: 10rpx;
}

.option-input {
  flex: 1;
  margin-right: 20rpx;
  font-size: 28rpx;
}

.color-picker {
  width: 48rpx;
  height: 48rpx;
  border-radius: 50%;
  overflow: hidden;
  border: 2rpx solid #ddd;
}

.color-preview {
  width: 100%;
  height: 100%;
}

.option-actions {
  display: flex;
  justify-content: flex-end;
  gap: 16rpx;
}

.option-actions .disabled {
  opacity: 0.3;
}

.add-option-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20rpx;
  border: 2rpx dashed #ddd;
  border-radius: 10rpx;
  margin-top: 20rpx;
  cursor: pointer;
}

.add-option-btn.disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.add-text {
  font-size: 28rpx;
  color: #11aaaa;
  margin-left: 10rpx;
}

.bottom-fixed {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 30rpx;
  background: #f5f5f5;
  box-shadow: 0 -4rpx 20rpx rgba(0, 0, 0, 0.05);
  z-index: 100;
}

.save-btn {
  background: #11aaaa;
  color: #fff;
  text-align: center;
  padding: 30rpx;
  border-radius: 10rpx;
  font-size: 32rpx;
  font-weight: bold;
}

.popup-content {
  background: #fff;
  border-radius: 20rpx 20rpx 0 0;
  padding: 30rpx;
}

.popup-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30rpx;
}

.popup-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.color-grid {
  display: grid;
  grid-template-columns: repeat(6, 1fr);
  gap: 20rpx;
}

.color-item {
  width: 80rpx;
  height: 80rpx;
  border-radius: 50%;
  border: 2rpx solid #eee;
  margin: 0 auto;
}
</style>
